<?php
class FileUtil{
	//Build a easy readable file size description
	public static function sizeStr($size = 0){
		$dw="B";
		if($size >= pow(2, 30)){
			$size=round($size/pow(2, 30), 2);
			$dw="G";
		}else if($size >= pow(2, 20)){
			$size=round($size/pow(2, 20), 2);
			$dw="M";
		}else if($size >= pow(2, 10)){
			$size=round($size/pow(2, 10), 2);
			$dw="K";
		}
		return $size.$dw;
	}
	
    public static function appendClickedBookId($id = 0){
        //Store the clicked book id in the keywords dir
        $keywordsDir = Yii::getPathOfAlias('application.keywords');
		$file = fopen($keywordsDir.'/bookids.log','a');
		fwrite($file,$id."\n");
		fclose($file);
    }
	public static function appendKeyword($keyword = ''){
		if($keyword === ''){
			return;
		}
		$keywordsDir = Yii::getPathOfAlias('application.keywords');
		$file = fopen($keywordsDir.'/keyword.log','a');
		fwrite($file,$keyword."\n");
		fclose($file);
	}
	
	public static function getAllKeywords(){
		$keywordsDir = Yii::getPathOfAlias('application.keywords');
		rename($keywordsDir.'/keyword.log',$keywordsDir.'/keyword.log.bak');
		$tmp = file($keywordsDir.'/keyword.log.bak');
        return self::trimnr($tmp);
	}
	
	public static function getAllBookIds(){
		$keywordsDir = Yii::getPathOfAlias('application.keywords');
		rename($keywordsDir.'/bookids.log',$keywordsDir.'/bookids.log.bak');
		$tmp = file($keywordsDir.'/bookids.log.bak');
        return self::trimnr($tmp);
	}

    public static function trimnr($lines = array()){
        if(empty($lines)){
            return array();
        }
        $ret = array();
        $len = count($lines);
        for($i=0;$i<$len;$i++){
            $ret[] = rtrim($lines[$i],"\n\r");
        }
        return $ret;
    }

	public static function getDataDir(){
		return Yii::getPathOfAlias('application.data');
	}
	
	public static function uploadBook($fileField = ''){
		$ret = array(
			'success'=>false,
			'message'=>'',
			'md5'=>'',
			'origin_name'=>'',
			'size'=>0,
			'book_path'=>''
		);
		$d = DIRECTORY_SEPARATOR;
		$dirPath = Yii::app()->params['uploadDir'].$d.'book'.$d.date('Y').$d.date('m').$d.date('d');
		$upload = new FileUploader($dirPath);
		$upload->MaxSize(Yii::app()->params['uploadBookMaxsize'])->AllowType(Yii::app()->params['uploadBookType']);
		if($upload->uploadFile($fileField)){
			$ret['success']=true;
			$ret['md5']=$upload->getMD5();
			$ret['origin_name']=self::getFileName($upload->getOriginName());
			$ret['size']=$upload->getSize();
			$ret['book_path']='/'.Yii::app()->params['uploadDir'].'/book/'.date('Y').'/'.date('m').'/'.date('d').'/'.$upload->getNewFileName();
			return $ret;
		} else {
			$ret['success'] = false;
			$ret['message'] = $upload->getErrorMsg();
			return $ret;
		}
	}
	
	public static function uploadBookPic($fileField = ''){
		$d = DIRECTORY_SEPARATOR;
		$dirPath = Yii::app()->params['uploadDir'].$d.'pic'.$d.date('Y').$d.date('m').$d.date('d');
		$upload = new FileUploader($dirPath);
		$upload->MaxSize(Yii::app()->params['uploadPicMaxsize'])->AllowType(Yii::app()->params['uploadPicType']);
		if($upload->uploadFile($fileField)){
			return '/'.Yii::app()->params['uploadDir'].'/pic/'.date('Y').'/'.date('m').'/'.date('d').'/'.$upload->getNewFileName();
		} else {
			return '';
		}		
	}
	
	public static function deleteBook($path){
		$path = ltrim($path,'/');
		if(!file_exists($path)){
			return;
		} else {
			unlink($path);
		}
	}
	
	public static function mkdirIfNotExists($dirPath = ''){
		if($dirPath === ''){
			return;
		}
		if(!file_exists($dirPath) || !is_writable($dirPath)){
			if(!@mkdir($this->filepath, 0755, true)){
				throw new CException("Mkdir {$dirPath} fail");
			}
		}
	}
	
    public static function getFileName($originName = ''){
        if($originName===''){
            throw new CException('Param originName is blank');
        }
        $pos = strrpos($originName,'.');
        return substr($originName,0,$pos);
    }

	public static function getExt($url = ''){
		if($url === ''){
			throw new CException('Param url is necessary');
		}
		$arr = explode('.',$url);
		return $arr[count($arr)-1];
	}

    //not test yet
    public static function delDir($dirname){
        if(file_exists($dirname)) {
            return;
        }
        $dir=opendir($dirname);
        while($filename=readdir($dir)){
            if($filename == "." || $filename == ".."){
                continue;
            }
            $file=$dirname."/".$filename;
            if(is_dir($file)){
                self::delDir($file); //del sub child dir
            }else{
                unlink($file);
            }
        }
        closedir($dir);
        rmdir($dirname);
    }

    //not test yet
    public static function copyDir($dirsrc, $dirto){
        if(is_file($dirto)){
            return;
        }
        if(!file_exists($dirto)){
            mkdir($dirto); 
        }
        $dir=opendir($dirsrc);
        while($filename=readdir($dir)){
            if($filename!="." && $filename!=".."){
                $file1=$dirsrc."/".$filename;
                $file2=$dirto."/".$filename;

                if(is_dir($file1)){
                    self::copyDir($file1, $file2); 
                }else{
                    copy($file1, $file2);
                }
            }
        }
        closedir($dir);
    }

    //not test yet
    public static function dirSize($dirname) {
        $dirsize=0;
        $dir=opendir($dirname);
        while($filename=readdir($dir)){
            $file=$dirname."/".$filename;
            if($filename!="." && $filename!=".."){
                if(is_dir($file)){
                    $dirsize+=self::dirSize($file); //递归完成	
                }else{
                    $dirsize+=filesize($file);
                }
            }
        }
        closedir($dir);
        return $dirsize;
    }
}
